//
//  RecordController.m
//  XSMusic
//
//  Created by 郝旭珊 on 2018/3/10.
//  Copyright © 2018年 郝旭珊. All rights reserved.
//

#import "RecordController.h"
#import <AVFoundation/AVFoundation.h>

@interface RecordController ()
@property (nonatomic, strong) AVAudioRecorder *recorder;
//定时器
@property (nonatomic, strong) NSTimer *mainTimer;
//调用一次经历了  1/60 秒
@property (nonatomic, strong) CADisplayLink *link;
@property (nonatomic, assign) CGFloat alltime;
@property (nonatomic, strong) AVAudioPlayer *player;


@end

@implementation RecordController



- (CADisplayLink *)link
{
    if (!_link) {
        _link = [CADisplayLink displayLinkWithTarget:self selector:@selector(mainUpdate)];
    }
    return _link;
}
- (void)mainUpdate
{
    //用户沉默两秒钟  停止
    //1.明确沉默的定义  不说话 <10分贝
    //获取分贝  不停的检车是否<10

    //2.看 是否够两秒
    //更新了参数
    [self.recorder updateMeters];

    //取最新的参数  平均值
    float power =  [self.recorder averagePowerForChannel:1];

    NSLog(@"%f",power);

    if (power < -30) { //沉默
        //累加当前的时间(1/60)
        self.alltime += 1/60.0;

        if (self.alltime >= 2.0) { //沉默两秒
            [self.recorder stop];
            NSLog(@"停止录音了!");
            [self.link invalidate];
            self.link = nil;
        }
        //突然的不沉默
    }else{
        self.alltime = 0;
    }
}

- (void)start{
    //开启定时器
    [self.link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    //开始录音
    [self.recorder record];
}

- (void)stop{
    [self.recorder stop];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self configureRecorder];
}


- (void)configureRecorder{
    //创建录音对象
    //保存路劲
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject]stringByAppendingPathComponent:@"123.caf"];

    NSURL *url = [NSURL fileURLWithPath:path];

    //字典是携带参数
    //文件名×
    NSMutableDictionary *setting = [NSMutableDictionary dictionary];
    //2.够着  录音参数
    // 音频格式
    setting[AVFormatIDKey] = @(kAudioFormatAppleIMA4);
    // 音频采样率
    setting[AVSampleRateKey] = @(8000.0);
    // 音频通道数
    setting[AVNumberOfChannelsKey] = @(1);
    // 线性音频的位深度
    setting[AVLinearPCMBitDepthKey] = @(8);

    self.recorder = [[AVAudioRecorder alloc]initWithURL:url settings:nil error:nil];
    self.recorder.meteringEnabled = YES;

}


- (BOOL)playMusic{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"我爱你你却爱着她.mp3" ofType:nil];
    NSURL *url = [NSURL fileURLWithPath:path];
    AVAudioPlayer *player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
    self.player = player;
    if ([player prepareToPlay]){
        return [player play];
    }

    return false;
}

- (void)playSound{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"m_03.wav" ofType:nil];
    NSURL *url = [NSURL fileURLWithPath:path];
    SystemSoundID soundID = 0;

    AudioServicesCreateSystemSoundID((__bridge CFURLRef)url, &soundID);
    AudioServicesPlaySystemSound(soundID);
}


@end
